package ${packageName}.service.impl;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ${packageName}.dao.IMutiTableDao;
import ${packageName}.service.IMutiTableService;
import ${packageName}.utils.CastUtil;
import ${packageName}.utils.ExcelUtil;

@Service
public class MutiTableService implements IMutiTableService {

	@Autowired
	private IMutiTableDao dao;

	private Map<String, Object> commonSelect(Map<String, Object> map, String modelName) throws Exception {

		List<String> orderData = CastUtil.cast(map.get("orderData"));

		String orderStr = "";
		for (int i = 0; i < orderData.size(); i++) {
			if (i == orderData.size() - 1) {
				orderStr += orderData.get(i);
				break;
			}
			orderStr += orderData.get(i) + ",";
		}

		Integer currentPage = (Integer) map.get("currentPage");

		Integer start = (currentPage - 1) * 10;

		Long totalPage = 1L;

		// sql中的start
		map.put("start", start);
		// 每页显示10条
		map.put("pageSize", 10);

		// 排序条件
		map.put("orderStr", orderStr);

		// 获取总个数
		Method getCountMethod = dao.getClass().getMethod(modelName + "SelectCount", Map.class);
		Long totalCount = (Long) getCountMethod.invoke(dao, map);

		Method getResultListMethod = dao.getClass().getMethod(modelName + "Select", Map.class);
		List<Map<String, Object>> resultList = CastUtil.cast(getResultListMethod.invoke(dao, map));

		if (totalCount != 0) {

			if (totalCount % 10 == 0) {
				totalPage = totalCount / 10;
			} else {
				totalPage = totalCount / 10 + 1;
			}

		}

		map.clear();
		// 当前页
		map.put("currentPage", currentPage);

		map.put("count", totalCount);

		map.put("totalPage", totalPage);

		map.put("result", resultList);

		return map;

	}
	
	<#list tablesQueryMap?keys as key>
	<#assign tableFiledModels = tablesQueryMap["${key}"].tableFiledModels/>
	/**
	 * ${key}查询
	 * 
	 */
	@Override
	public Map<String, Object> ${key}Select(Map<String, Object> map) {
	
		try {
			return commonSelect(map, "${key}");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
		
	}
	
	/**
	 * ${key}导出excel
	 * 
	 */
	@Override
	public void ${key}ExportExcel(Map<String, Object> paramMap, HttpServletResponse response) {

		// 获取头部信息
		String[] headList = new String[] {<#list tableFiledModels as data> "${data.filedText_cn}"<#if data_has_next>,</#if></#list>};

		String[] describeList = new String[] {<#list tableFiledModels as data> "${data.filedCommentStr}"<#if data_has_next>,</#if></#list>};

		try {
			ExcelUtil.mutiTablexportExcel(paramMap, response, dao, "${key}", headList, describeList);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	</#list>
}
